package net.csdn.business.common.utils;

import com.netease.yidun.sdk.antispam.image.v5.check.ImageV5CheckRequest;
import com.vladsch.flexmark.ast.Image;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.util.data.MutableDataSet;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import net.csdn.business.common.domain.pop.dto.AnalysisImgDto;
import net.csdn.business.common.enums.AuditStateEnum;
import net.csdn.business.common.exception.BusinessException;
import net.csdn.business.common.yidun.AsyncImageResponse;
import net.csdn.business.common.yidun.image.v5.ImageSyncCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.checkerframework.checker.units.qual.A;
import org.jsoup.Jsoup;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.jsoup.nodes.Element;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ContentAnalysisUtil {

    public static String convertDoc(InputStream inputStream){
        try{
            //构造函数放入文件流得到HWPFDocument对象
            HWPFDocument hwpfDocument = new HWPFDocument(inputStream);
            //构造WordToHtmlConverter对象
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

            //开始解析doc文档
            wordToHtmlConverter.processDocument(hwpfDocument);
            Document document = wordToHtmlConverter.getDocument();
            //通过TransformerFactory创造出Transformer ,并设置Transformer的属性
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT,"yes");
            transformer.setOutputProperty(OutputKeys.METHOD,"html");

            //transformer.transform()需要参数1 Source 参数2 Result
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream outputtarget = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(outputtarget);
            //开始转换,结果数据在ByteArrayOutputStream里
            transformer.transform(domSource,streamResult);//参数1 Source 参数2 Result

            //转成字符串看看
            return outputtarget.toString("utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertDocx(InputStream inputStream){
        try {
            //创建操作docx word的对象
            XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
            //解析XHTML配置
            XHTMLOptions xhtmlOptions = XHTMLOptions.create();
            // 将样式都写为内联样式，而不是写到style标签中 默认false
            xhtmlOptions.setFragment(true);
            xhtmlOptions.setIgnoreStylesIfUnused(false);
            xhtmlOptions.setImageManager(new Base64EmbedImgManager());//图片用base64转化

            //将XWPFDocument转化成HTML
            ByteArrayOutputStream outputtarget = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(xwpfDocument,outputtarget,xhtmlOptions);

            //转成字符串看看
            return outputtarget.toString("utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertMarkdown(InputStream inputStream){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                stringBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return stringBuilder.toString();
    }

//    public static String convertMarkdown(InputStream inputStream){
//        StringBuilder stringBuilder = new StringBuilder();
//        try {
//            byte[] buffer = new byte[2048];
//            int bytesRead;
//            while ((bytesRead = inputStream.read(buffer)) !=-1){
//                stringBuilder.append(new String(buffer,0,bytesRead, StandardCharsets.UTF_8));
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return stringBuilder.toString();
//    }

    public static String cleanTextForMarkdown(String content){
        if(StringUtils.isEmpty(content)){
            return "";
        }
        MutableDataSet options = new MutableDataSet();
        Parser parser = Parser.builder(options).build();
        Node node = parser.parse(content);
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
        return cleanTextForHtml(renderer.render(node));
    }

    public static String cleanTextForHtml(String content){
        if(StringUtils.isEmpty(content)){
            return "";
        }
        org.jsoup.nodes.Document document = Jsoup.parse(content);
        Jsoup.clean(document.html()
                ,""
                ,org.jsoup.safety.Safelist.none()
                ,new org.jsoup.nodes.Document.OutputSettings().prettyPrint(false));
        return document.text();
    }

    public static List<AnalysisImgDto> docImg(String content){
        List<AnalysisImgDto> imgContentList = new ArrayList<>();
        if(StringUtils.isEmpty(content)){
            return imgContentList;
        }
        org.jsoup.nodes.Document document = Jsoup.parse(content);
        org.jsoup.select.Elements imgElements = document.select("img");
        for(Element img : imgElements){
            AnalysisImgDto analysisImgDto = new AnalysisImgDto();
            String srcContent = img.attr("src");
            if(srcContent.startsWith("data")){
                String base64Content = srcContent.split(",")[1];
                analysisImgDto.setType(2);
                analysisImgDto.setImgContent(base64Content);
            }else {
                analysisImgDto.setType(1);
                analysisImgDto.setImgContent(srcContent);
            }
            imgContentList.add(analysisImgDto);
        }
        return imgContentList;
    }

    public static String docReplaceImg(String content,Map<Integer,String> imgMap){
        if(StringUtils.isEmpty(content)){
            return content;
        }
        org.jsoup.nodes.Document document = Jsoup.parse(content);
        org.jsoup.select.Elements imgElements = document.select("img");
        Integer i=0;
        for(Element img : imgElements){
            if(imgMap.containsKey(i)){
                img.attr("src",imgMap.get(i));
            }
            i++;
        }
        return document.html();
    }

    public static List<AnalysisImgDto> mdImg(String content){
        List<AnalysisImgDto> imgContentList = new ArrayList<>();
        MutableDataSet options = new MutableDataSet();
        Parser parser = Parser.builder(options).build();
        Node node = parser.parse(content);

        for (Node child : node.getChildren()) {
            if(child instanceof Image){
                Image image = (Image) child;
                String srcContent = image.getUrlContent().toString();

                AnalysisImgDto analysisImgDto = new AnalysisImgDto();
                if(srcContent.startsWith("data")){
                    String base64Content = srcContent.split(",")[1];
                    analysisImgDto.setType(2);
                    analysisImgDto.setImgContent(base64Content);
                }else {
                    analysisImgDto.setType(1);
                    analysisImgDto.setImgContent(srcContent);
                }
                imgContentList.add(analysisImgDto);
            }
        }
        return imgContentList;
    }

    public static String mdReplaceImg(String content,Map<Integer,String> imgMap){
        if(imgMap.isEmpty() || StringUtils.isEmpty(content)){
            return content;
        }
        MutableDataSet options = new MutableDataSet();
        Parser parser = Parser.builder(options).build();
        Node node = parser.parse(content);
        Integer i=0;
        for (Node child : node.getChildren()) {
            if(child instanceof Image){
                if(imgMap.containsKey(i)){
                    Image image = (Image) child;
                    image.setUrlContent(BasedSequence.of(imgMap.get(i)));
                }
                i++;
            }
        }
        return parser.toString();
    }
}
